#!/usr/bin/env python3
#coding=utf-8
#請執行本程式以啟動lonote

import os, sys, optparse, locale, shelve, glob

from PyQt4.QtGui import *
from PyQt4.QtCore import *

#測試匯入成功或否，如果匯入失敗，追加匯入路徑
try:
    import lonote.path as path
except:
    sys.path.append('/usr/lib/python3/dist-packages')
    import lonote.path as path

import lonote.translate as translate
import lonote.main as main
from lonote.version import version

cfg = path.fix.cfg

status = shelve.open(filename = cfg, protocol = 3, writeback = True)

#準備處理變數與Help說明
programDescription = _('''\
LoNote is a Note-Taking software which using Python3 and PyQt4.''')

programUsage = _('''%prog [Options] [FOLDER]
  FOLDER = LoNote's notebook folder
  If you aren't using any option, LoNote will open the
  mainwindow by default.''')

parser = optparse.OptionParser(
        description = programDescription,
        usage = programUsage,
        version = version)
parser.add_option('-d',
        dest = 'default',
        action = 'store_const' ,
        const = True,
        help = _('Open with default setting.'))
parser.add_option('-w',
        dest = 'default_window',
        action = 'store_const' ,
        const = True,
        help = _('Open with default window layout.'))
parser.add_option('-l',
        dest = 'language',
        help = _('set LANGUAGE like "zh_TW". "default" mean using system language. "nolocale" mean no locale support (english).'))
parser.add_option('', '--lang',
        dest = 'languages',
        action = 'store_const' ,
        const = True,
        help = _('Show support LANGUAGE.'))
parser.add_option('', '--example',
        dest = 'example',
        action = 'store_const' ,
        const = True,
        help = _('Open with exmaple notebook.'))
opts, args = parser.parse_args() #讀入命令行變數


#處理變數

#如果有 --example 參數，強制打開example
if opts.example:
    status['ISEXAMPLE'] = True

#如果有language參數，重設語言檔，隨後退出
if opts.language:
    translate.saveLanguageFile(opts.language)
    print(_('LoNote\'s language now be assigned to {$LANG}!').replace('{$LANG}', opts.language))
    sys.exit()

#如果有languages參數，顯示資料，隨後退出
if opts.languages:
    print(_('LoNote support the following language:'))
    print('----------------------------')
    for code, name in translate.validLanguages:
        print('{0:<4}{1:<10}:{2}'.format('', code, name))
    print('----------------------------')
    print(_('LoNote\'s language now be assigned to {$LANG}!').replace('{$LANG}', translate.loadLocaleSetting()))
    print(_('Your system\'s default language is {$LANG}!').replace('{$LANG}', locale.getdefaultlocale()[0]))
    print('----------------------------')
    print(_('If you assign any INVALID language code with "-l", you will disable the LoNote\'s locale support. until user re-assign a new valid code instead.'))
    sys.exit()

#如果有 -d 參數，以預設的設定值執行
if opts.default:
    status.close()
    status = None
    for filepath in glob.iglob(cfg + '*'):
        os.remove(filepath)

#如果有 -w 參數，以預設的視窗顯示狀態執行
elif opts.default_window:
    status['WINDOW_WIDTH'] = 0
    status['WINDOW_HEIGHT'] = 0
    status['WINDOW_MAXIMIZED'] = False
    status['RIGHT_SPLITTER_SIZES'] = None
    status['MAIN_SPLITTER_SIZES'] = None
    status['RD_SPLITTER_SIZES'] = [1,0]
    status['SHOW_INNERTITLE'] = False
    status['LEFTTAB_POS'] = 0

#如果有指定筆記路徑，則代換currentNoteBook，等會兒就能讀取。
if args:
    PATH = os.path.abspath(args[0])
    print(_('loading: ') + PATH)
    #確認路徑合法
    if not (
            os.path.isdir(PATH) and
            os.path.isfile(path.cal.bookdb(PATH))):
        print(_('The path not valid, I can\'t open it.'))
        sys.exit(2)
    status['ISEXAMPLE'] = False
    status['BOOKDIR'] = PATH

#主程式開始執行
#QT程式初始化
app = QApplication(sys.argv)

main = main.LoMain(status = status, app = app)

main.show()
#啟動QT
app.exec_()
